import { ApiResponse, LoginForm, Token } from '@/types/data'
import { LoginAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { removeToken, setToken } from '@/utils/storage'

// 用户登录
export const login = (values:LoginForm): RootThunkAction => {
  return async (dispatch) => {
    //   Token:本接口返回值的类型
    const res = await request.post<ApiResponse<Token>>('/authorizations', values)

    // 持久化
    setToken(res.data.data)
    // 保存redux
    dispatch({
      type: 'login/token',
      payload: res.data.data
    })
  }
}

// 获取验证码
export const getCode = (mobile:string): RootThunkAction => {
  return async (dispatch) => {
    //  调用接口
    await request.get('/sms/codes/' + mobile)
  }
}

// 用户退出
export const logout = (): LoginAction => {
  // 持久化
  removeToken()
  // 保存redux
  return {
    type: 'login/logout'
  }
}

export const saveToken = (token: Token):LoginAction => {
  // 1. 本地localstorage
  setToken(token)
  // 2. redux
  return {
    type: 'login/token',
    payload: token
  }
}
